package com.jse.io.nio.mynio;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class AServer {
	public static void main(String[] args) throws Exception {
		ServerSocketChannel server = ServerSocketChannel.open();
		server.configureBlocking(false);
		server.socket().bind(new InetSocketAddress(8080));
		Selector selector = Selector.open();
		server.register(selector, SelectionKey.OP_ACCEPT);

		while (true) {
			selector.select();
			System.out.println("selector.select()---------");
			// readKeys集合
			Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
			while (iter.hasNext()) {
				SelectionKey key = iter.next();
				iter.remove();

				if (key.isAcceptable()) {
					System.out.println("acceptable");
					// ServerSocketChannel ssc = (ServerSocketChannel)
					// key.channel();
					SocketChannel client = server.accept();
					client.configureBlocking(false);
					client.register(selector, SelectionKey.OP_WRITE);
				} else if (key.isWritable()) {
					System.out.println("this server is writeable");
//					SocketChannel c = server.
				}
			}
		}
	}
}
